package cn.ckx.coding.common.validation;

import javax.validation.*;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * 枚举校验
 * 
 * @author kunxin.cai
 **/
@Documented
@Constraint(validatedBy = {EnumValid.EnumValidator.class})
@Target(ElementType.PARAMETER)
@Retention(RUNTIME)
public @interface EnumValid {

    String message() default "{cn.ckx.coding.common.validation.EnumValid.message}";

    Class<?>[] groups() default { };
                                                                                        
    Class<? extends Payload>[] payload() default { };

    /**
     * 不包含的枚举参数数组
     */
    String[] exclusives() default { };

    class EnumValidator implements ConstraintValidator<EnumValid,Enum> {

        private Set<String> exclusiveEnums = new HashSet<>();

        @Override
        public void initialize(EnumValid constraintAnnotation) {
            String[] strings = constraintAnnotation.exclusives();
            if (strings.length>0){
                exclusiveEnums.addAll(Arrays.asList(strings));
            }
        }

        @Override
        public boolean isValid(Enum value, ConstraintValidatorContext constraintValidatorContext) {
            return !exclusiveEnums.contains(String.valueOf(value));
        }

    }

     

}
